import { getSorter, useRequestHandle } from '@/utils/utils';
import {
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { ProDescriptions } from '@ant-design/pro-components';
import {
  Button,
  Drawer,
  message,
  Space, Badge
} from 'antd';
import { useRef, useState } from 'react';
import { Access, useAccess } from 'umi';
import operation from './operation';
import SaveForm from './components/SaveForm';
import EditFile from './components/EditFile';

import { addOrUpdate, query, getHealthy } from './service';
import ProMaxTable from '@/components/ProMaxTable';
import { useUpdateEffect } from '@umijs/hooks';
const Env = (props) => {
  const { agentServerId, agentAddress } = props;
  const [saveFormVisible, setSaveFormVisible] = useState(false);
  const [editFileVisible, setEditFileVisible] = useState(false);
  const [updateFormValues, setUpdateFormValues] = useState({});
  const [healthy, setHealthy] = useState(false);
  const actionRef = useRef();
  const [row, setRow] = useState();
  const { canOperation, canShowOption } = useAccess();
  // 是否显示操作列
  const isShowOptionColumn = canShowOption([
    operation.update
  ]);

  // 刷新
  const reload = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  // 新增/修改
  const addOrUpdateRequest = useRequestHandle(addOrUpdate, () => {
    message.success('创建成功.');
    setSaveFormVisible(false);
    reload();
  });

  const getHealthyRequest = useRequestHandle(getHealthy, () => {
    setHealthy(true);
  });
  useUpdateEffect(() => {
    reload();

  }, [agentServerId]);

  const getHealthyCheck = () => {


    if (getHealthyRequest.loading) {
      return <Badge status="processing" text="检查中" />
    }

    if (healthy) {
      return <Badge status="success" text="服务器在线" />
    }

    return <Badge status="error" text="服务器离线" />




  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      fixed: 'left',
      width: 75,
    },
    {
      title: '服务名称',
      dataIndex: 'serverName',
      ellipsis: true,
      render: (dom, entity) => <a onClick={() => setRow(entity)}>{dom}</a>,
      fixed: 'left',
      width: 170,
    },
    {
      title: '服务根目录',
      dataIndex: 'rootPath',
      ellipsis: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,

    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      hideInTable: !isShowOptionColumn,
      width: 180,
      render: (_, record) => (
        <Space>
          <Access accessible={canOperation(operation.update)}>
            <Button
              type="primary"
              size="small"
              onClick={async () => {

                setSaveFormVisible(true);
                setUpdateFormValues(record);
              }}
            >
              编辑
            </Button>
          </Access>
          <Access accessible={canOperation(operation.agentSaveFileText)}>
            <Button
              type="primary"
              size="small"
              onClick={async () => {
                setEditFileVisible(true);
                setUpdateFormValues(record);
              }}
            >
              修改文件
            </Button>
          </Access>
        </Space>
      ),
    },
  ];
  return (
    <>
      <Space style={{ padding: "0 24px" }}>
        {agentAddress}
        {getHealthyCheck()}
        <Button icon={<ReloadOutlined />}
          onClick={() => {
            getHealthyRequest.run({ id: agentServerId });
          }}
          type="primary" size={"small"}>重新检查</Button>
      </Space>
      <ProMaxTable
        headerTitle={"配置"}
        actionRef={actionRef}
        cardProps={{
          style: { height: "auto" }
        }}
        rowKey="id"
        search={false}
        options={{
          search: canOperation(operation.query)
            ? {
              placeholder: '请输入关键字',
            }
            : false,
          fullScreen: true,
        }}
        toolBarRender={() => [
          <Access key="create" accessible={canOperation(operation.update)}>
            <Button type="primary" onClick={() => {
              if (healthy) {
                setSaveFormVisible(true)
              }
              else {
                message.error("服务器离线，请检查服务器状态！")
              }
            }}>
              <PlusOutlined /> 创建
            </Button>
          </Access>,

        ]}
        request={async (params, sorter, filter) => {
          getHealthyRequest.run({ id: agentServerId });
          const data = params;
          data.pageIndex = params.current;
          data.agentServerId = agentServerId;
          const result = await query({ ...data, ...getSorter(sorter), filter });
          if (result.success) {
            return {
              ...result,
              total: result.data.totalItems,
            };
          }
          return [];
        }}
        postData={(data) => {
          return !data ? [] : data.items;
        }}
        // scroll={{
        //   x: 1200,
        // }}
        columns={columns}
        rowSelection={false}
        expandable={{ defaultExpandAllRows: true }}
      />

      <SaveForm
        onSubmit={async (value) => {
          const params = { ...value }
          params.agentServerId = agentServerId;
          addOrUpdateRequest.run(params);
        }}
        onCancel={() => {
          setSaveFormVisible(false);
          setUpdateFormValues({});
        }}
        id={agentServerId}
        loading={addOrUpdateRequest.loading}
        modalVisible={saveFormVisible}
        record={updateFormValues}
      />
      <EditFile
        onSubmit={async () => {
          // const params = { ...value }
          // params.agentServerId = agentServerId;
          // addOrUpdateRequest.run(params);
        }}
        onCancel={() => {
          setEditFileVisible(false);
          setUpdateFormValues({});
        }}
        id={agentServerId}
        loading={addOrUpdateRequest.loading}
        modalVisible={editFileVisible}
        record={updateFormValues}
      />
      <Drawer
        width={600}
        open={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.id && (
          <ProDescriptions
            column={2}
            title={row?.realName}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.id,
            }}
            columns={columns}
          />
        )}
      </Drawer>


    </>
  );
};

export default Env;
